<?php
namespace App\Admin\Models;
use Common\BaseModel;
use Common\CommonAd;

class Orders extends BaseModel
{
    protected $res;
    public $key;

    public function getSource()
    {
        return "w_union_order";
    }

    public function initialize()
    {
        parent::initialize();
        $this->hasMany('id', 'OrderCommisions', 'order_id');
    }

    public function orderCountTime($data)
    {
        $where = "created_at >= '{$data['start_at']}' and created_at <= '{$data['end_at']}'";
        return $this::count($where);
    }

    public function get_list($data)
    {
        $conditions = 'id>0';
        if (isset($data['start_time']) && !empty($data['start_time'])) {
            $conditions .= " and order_create_time >= '{$data['start_time']}'";
        }
        if (isset($data['end_time']) && !empty($data['end_time'])) {
            $conditions .= " and order_create_time <= '{$data['end_time']}'";
        }
        if (isset($data['phone']) && !empty($data['phone'])) {
            $userDb    = new User();
            $userWhere = "phone = '{$data['phone']}' or nickname = '{$data['phone']}' or invite_code = '{$data['phone']}'";
            $info      = $userDb->findFirst($userWhere);
            if (!$info) {
                $result['total'] = 0;
                $result['list']  = [];
                return $result;
            }
            $conditions .= " and user_id = '{$info->id}'";
        }

        if (isset($data['invite_code']) && !empty($data['invite_code'])) {
            $userDb    = new User();
            $userWhere = "invite_code = '{$data['invite_code']}' or exclusive_code = '{$data['invite_code']}'";
            $info      = $userDb->findFirst($userWhere);
            if (!$info) {
                $result['total'] = 0;
                $result['list']  = [];
                return $result;
            }
            $conditions .= " and user_id = '{$info->id}'";
        }

        if (isset($data['goods_name']) && !empty($data['goods_name'])) {
            $conditions .= " and goods_name like '%{$data['goods_name']}%'";
        }
        if (isset($data['is_free']) && $data['is_free'] == 1) {
            $f_order_commissions = new OrderCommissions();
            $where['conditions'] = "is_free = 1";
            $where['columns']    = "order_id";
            $where['group']      = "order_id";
            $orders              = $f_order_commissions->find($where)->toarray();

            if (!empty($orders)) {
                $orderIds   = implode(',', array_column($orders, 'order_id'));
                $conditions .= " and order_id in ($orderIds)";
            } else {
                $result['total'] = 0;
                $result['list']  = [];
                return $result;
            }
        }
        if (isset($data['site']) && !empty($data['site'])) {
            $conditions .= " and site = '{$data['site']}'";
        }

        if (isset($data['order_id']) && !empty($data['order_id'])) {
            $conditions .= " and order_id  like '{$data['order_id']}%'";
        }

        if (isset($data['order_status']) && $data['order_status'] > 0) {
            $conditions .= " and order_status  = {$data['order_status']}";
        }

        $page = isset($data['page']) ? $data['page'] : 1;
        $size = isset($data['limit']) ? $data['limit'] : 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }

        $count = $this::count($conditions);
        if ($count > 0) {
            $newconditions = $conditions .' and order_status in (2,4,6)';
            $countData                    = $this::find(array(
                $newconditions,
                'columns' => 'commition,order_id,commition',
            ))->toarray();
            $result['estimate_commition'] = 0;
            $result['estimate_profit']    = 0;
            if (!empty($countData)) {

                foreach ($countData as $eval) {
                    $result['estimate_commition'] += $eval['commition'];
                    $common                       = new OrderCommissions();
                    $where['conditions']          = "order_id = '{$eval['order_id']}'";
                    $where['columns']             = "sum(money) as money ,commission_type";
                    $where['group']               = "commission_type";
                    $commonList                   = $common->find($where)->toarray();
                    $zigou                        = 0;
                    $fenyon                       = 0;
                    $shengyu                      = $eval['commition'];
                    if (!empty($commonList)) {
                        foreach ($commonList as $vals) {
                            if ($vals['commission_type'] == 1) {
                                $zigou = $vals['money'];
                            } else {
                                $fenyon = $vals['money'];
                            }
                        }
                        $shengyu = CommonAd::number_randtwo($shengyu - $zigou - $fenyon);
                    }
                    $result['estimate_profit'] += $shengyu;
                }
            }

            $cate_list       = $this::find(
                array(
                    $conditions,
                    "order"  => 'order_paid_time desc',
                    //                "columns" => 'id,cid,item_id,title,short_title,shop_type,pic_logo,coupon_money,price,end_price,month_sale,site,created_at,updated_at,top,status',
                    'limit'  => $size,
                    'offset' => $page
                ));
            $result['total'] = $count;

            $result['list'] = $cate_list->toarray();
            $user           = new User();
            foreach ($result['list'] as $key => $val) {
                $userInfo = $user->findFirstById($val['user_id']);
                if ($userInfo) {
                    $result['list'][$key]['nickname'] = $userInfo->nickname ? $userInfo->nickname : substr_replace($userInfo->phone, '****', 3, 4);
                } else {
                    $result['list'][$key]['nickname'] = '用户未找到!';
                }
                $result['list'][$key]['o_site'] = $val['site'];
                switch ($val['site']) {
                    case 'haodanku':
                        $site = '淘宝';
                        break;
                    case 'jd':
                        $site = '京东';
                        break;
                    case 'pdd':
                        $site = '拼多多';
                        break;
                    case 'elm':
                        $site = '饿了么';
                        break;
                    case 'vph':
                        $site = '唯品会';
                        break;
                    case 'suning':
                        $site = '苏宁';
                        break;
                    default:
                        $site = '未知';
                }
                $result['list'][$key]['site'] = $site;

                $common                          = new OrderCommissions();
                $where['conditions']             = "order_id = '{$val['order_id']}'";
                $where['columns']                = "sum(money) as money ,commission_type";
                $where['group']                  = "commission_type";
                $commonList                      = $common->find($where)->toarray();
                $result['list'][$key]['zigou']   = 0;
                $result['list'][$key]['fenyong'] = 0;
                $result['list'][$key]['shengyu'] = $val['commition'];
                if (!empty($commonList)) {
                    foreach ($commonList as $vals) {
                        if ($vals['commission_type'] == 1) {
                            $result['list'][$key]['zigou'] = $vals['money'];
                        } else {
                            $result['list'][$key]['fenyong'] = $vals['money'];
                        }
                    }
                    $result['list'][$key]['shengyu'] = CommonAd::number_randtwo($val['commition'] - $result['list'][$key]['zigou'] - $result['list'][$key]['fenyong']);
                    $result['list'][$key]['fenyong'] = CommonAd::number_randtwo($result['list'][$key]['zigou'] + $result['list'][$key]['fenyong']);
                }
                $result['list'][$key]['yuliu_money'] = CommonAd::number_randtwo($val['commition'] - $val['commition']);
                if ($val['commition'] == 0 || $val['commition'] == 0) {
                    $result['list'][$key]['yuliu_ratio'] = 0;
                } else {
                    $yuliu_ratio                         = CommonAd::number_randtwo(1 - $val['commition'] / $val['commition'], 5) * 100;
                    $result['list'][$key]['yuliu_ratio'] = $yuliu_ratio . '%';
                }

                //利润比例
                $profit_ratio                         = $val['commition'] == 0 ? 0 : $result['list'][$key]['shengyu'] / $val['commition'] * 100;
                $result['list'][$key]['profit_ratio'] = CommonAd::number_randtwo($profit_ratio) . '%';
            }
        } else {
            $result['total']              = 0;
            $result['list']               = [];
            $result['estimate_commition'] = 0;
            $result['estimate_profit']    = 0;
        }
        return $result;
    }

    public function orderTop($data)
    {
        $where = 'order_status in (2,4,6) ';
        $group = 'goods_id';
        if (isset($data['goods_name']) && !empty($data['goods_name'])) {
            $where .= " and goods_name = '{$data['goods_name']}'";
        }
        if (isset($data['invite_code']) && !empty($data['invite_code'])) {
            $userDb    = new User();
            $userWhere = "invite_code = '{$data['invite_code']}' or exclusive_code = '{$data['invite_code']}'";
            $info      = $userDb->findFirst($userWhere);
            if (!$info) {
                return [];
            }
            $where .= " and user_id = '{$info->id}'";
        }
        if (isset($data['start_time']) && !empty($data['start_time'])) {
            $where .= " and order_create_time >= '{$data['start_time']}'";
        }
        if (isset($data['end_time']) && !empty($data['end_time'])) {
            $where .= " and order_create_time <= '{$data['end_time']}'";
        }
        $cate_list = $this::find(
            array(
                $where,
                'columns' => 'sum(commition) as commition,goods_name,goods_id,goods_pic, sum(pay_money) as pay_money,count(*) as count',
                "order"   => 'commition desc',
                'limit'   => 30,
                'group'   => $group,
            ))->toarray();
        return $cate_list;
    }


    /**
     * @func 根据用户时间获取各个平台的数据总和 自购订单数量
     * @param $user_id 用户id
     * @param $start_end_time 开始时间和结束时间
     * @param $order_channel 所属平台 taobao pinduoduo jd 如果没有，则查找三个平台的总和
     * @return array 以平台名称作为键 统计作为结果
     */
    public function getOrderCount($user_id, $start_end_time, $order_channel = '')
    {
        if ($order_channel) {
            $conditions = "user_id = ?1 AND order_create_time >= ?2 AND order_create_time < ?3 AND site = ?4";
            $parameters = array(1 => $user_id, 2 => $start_end_time['start_at'], 3 => $start_end_time['end_at'], 4 => $order_channel);
        } else {
            $conditions = "user_id = ?1 AND order_create_time >= ?2 AND order_create_time < ?3";
            $parameters = array(1 => $user_id, 2 => $start_end_time['start_at'], 3 => $start_end_time['end_at']);
        }
        $count_array = $this::count(array(
            $conditions,
            "column" => "*",
            "group"  => "site",
            "bind"   => $parameters
        ));
        $new_array   = array();
        foreach ($count_array as $key => $value) {
            $new_array[$value['site']] = $value['rowcount'];//order_channel
        }
        return $new_array;
    }


    /**
     * 获取个人自己出单和粉丝出单
     * @param $param
     * @return mixed
     */
    public function getOrderList($param)
    {
        if ($param['commission_type'] == 1) {//自推出单
            $conditions = "OrderCommissions.user_id =" . $param['user_id'] . ' and  OrderCommissions.commission_type=1';
        } else {//粉丝出单
            $conditions = "OrderCommissions.user_id =" . $param['user_id'] . ' and OrderCommissions.commission_type=2';
        }
        if (isset($param['order_status']) && !empty($param['order_status'])) {
            $conditions .= " AND Orders.order_status IN (" . $param['order_status'] . ")";
        }
        if (isset($param['tk_create_time']) && !empty($param['tk_create_time'])) {
            if ($param['tk_create_time'][0] && empty($param['tk_create_time'][1])) {
                $conditions .= " And OrderCommissions.tk_create_time >= '{$param['tk_create_time'][0]}'";
            }
            if ($param['tk_create_time'][1] && empty($param['tk_create_time'][0])) {
                $conditions .= " And OrderCommissions.tk_create_time <= '{$param['tk_create_time'][1]}'";
            }
            if ($param['tk_create_time'][0] && $param['tk_create_time'][1]) {
                $conditions .= " And OrderCommissions.tk_create_time >= '{$param['tk_create_time'][0]}' And OrderCommissions.tk_create_time <= '{$param['tk_create_time'][1]}'";
            }
        }
        $phql = "SELECT Orders.id,Orders.user_id,Orders.order_id,Orders.order_status,Orders.goods_name,Orders.goods_id,Orders.goods_pic,Orders.site,Orders.price,Orders.pay_money,Orders.commition,Orders.income_rate,Orders.order_create_time,Orders.order_paid_time,Orders.order_earning_time,Orders.is_settlement,
                OrderCommissions.money,OrderCommissions.money_plus,OrderCommissions.commission_type,OrderCommissions.tk_create_time
                FROM OrderCommissions LEFT JOIN Orders ON Orders.order_id = OrderCommissions.order_id
				where  " . $conditions . "  GROUP BY Orders.user_id,Orders.order_id  order by Orders.order_create_time DESC";
        $rows = $this->modelsManager->executeQuery($phql);
        return $rows;
    }


    /**
     * 获取个人自己出单和粉丝出单
     * @param $param
     * @return mixed
     */
    public function getOrderList_list($param)
    {
        $beg = $param['page'] <= 1 ? 0 : ($param['page'] - 1) * $param['page_size'];
        $end = $param['page_size'];
//        if ($param['commission_type'] == 1) {//自推出单
//            $conditions = "OrderCommissions.user_id =" . $param['user_id'] . ' and  OrderCommissions.commission_type=1';
//        } else {//粉丝出单
//            $conditions = "OrderCommissions.user_id =" . $param['user_id'] . ' and OrderCommissions.commission_type=2';
//        }
        $conditions = "Orders.commition<>0";
        if (isset($param['order_status']) && !empty($param['order_status'])) {
            $conditions .= " AND Orders.order_status IN (" . $param['order_status'] . ")";
        }
        if (isset($param['keywords']) && !empty($param['keywords'])) {
            $conditions .= " AND Orders.goods_name like '%{$param['keywords']}%'";
        }
        if (isset($param['site']) && !empty($param['site'])) {
            $conditions .= " and Orders.site = '{$param['site']}' ";
        }
        if (isset($param['tk_create_time']) && !empty($param['tk_create_time'])) {
            if ($param['tk_create_time'][0] && empty($param['tk_create_time'][1])) {
                $conditions .= " And OrderCommissions.tk_create_time >= '{$param['tk_create_time'][0]}'";
            }
            if ($param['tk_create_time'][1] && empty($param['tk_create_time'][0])) {
                $conditions .= " And OrderCommissions.tk_create_time <= '{$param['tk_create_time'][1]}'";
            }
            if ($param['tk_create_time'][0] && $param['tk_create_time'][1]) {
                $conditions .= " And OrderCommissions.tk_create_time >= '{$param['tk_create_time'][0]}' And OrderCommissions.tk_create_time <= '{$param['tk_create_time'][1]}'";
            }
        }
        $phql            = "SELECT Orders.id,Orders.user_id,Orders.order_id,Orders.order_status,Orders.goods_name,Orders.goods_id,Orders.goods_pic,Orders.site,Orders.price,Orders.pay_money,Orders.commition,Orders.income_rate,Orders.order_create_time,Orders.order_paid_time,Orders.order_earning_time,Orders.is_settlement,
                OrderCommissions.money,OrderCommissions.money_plus,OrderCommissions.commission_type,OrderCommissions.tk_create_time
                FROM OrderCommissions LEFT JOIN Orders ON Orders.order_id = OrderCommissions.order_id
				where  " . $conditions . " ORDER BY Orders.order_create_time DESC LIMIT $beg,$end ";
        $items           = $this->modelsManager->executeQuery($phql);
        $result['items'] = $items->toarray();

        $phql                  = "SELECT count(*) as counts FROM OrderCommissions LEFT JOIN Orders ON Orders.order_id = OrderCommissions.order_id
				where  " . $conditions . " ";
        $total_items           = $this->modelsManager->executeQuery($phql);
        $result['total_items'] = $total_items->toarray() ? $total_items->toarray()[0]['counts'] : 0;

        return $result;
    }


    /**
     * 查询我的订单数数量
     */
    public function getSelfOrders($user_id)
    {
        $conditions  = "order_status in (2,4,6) AND user_id = ?1";
        $parameters  = array(1 => $user_id);
        $count_array = $this:: count(array(
            $conditions,
            "column" => "*",
            "bind"   => $parameters
        ));
        return $count_array;
    }

    public function find_back_order($order_id, $user_id, $type)
    {
        $conditions = "order_id = '$order_id' and user_id = '0'";
        $res        = $this->findFirst($conditions);
        if ($res) {
            if ($type == 'find') {
                return $res->toarray();
            }
            $res->user_id              = $user_id;
            $res->is_calculation_money = 0;
            $res->remark               = date('Y-m-d H:i:s') . '找回订单';
            $res->save();

            return $res->toarray();
        }
        return false;
    }

    public function orderStatistics($st, $order_status)
    {
        $where['columns']    = "DATE_FORMAT(order_create_time, '%Y-%m-%d') AS MONTH , sum(commition) AS commition";
        $where['conditions'] = "order_status in ($order_status) and order_create_time >= '{$st['start_at']}' AND order_create_time <= '{$st['end_at']}'";
        $where['group']      = "MONTH";
        $where['order']      = "order_create_time asc";
        $list                = $this->find($where)->toarray();
        $result              = [];
        if (!empty($list)) {
            foreach ($list as $val) {
                $result[$val['MONTH']] = $val['commition'];
            }
        }
        return $result;
    }

    public function orderStatisticsMonth($st, $order_status)
    {
        $where['columns']    = "DATE_FORMAT(order_create_time, '%Y-%m') AS MONTH , sum(commition) AS commition";
        $where['conditions'] = "order_status in ($order_status) and order_create_time >= '{$st['start_at']}' AND order_create_time <= '{$st['end_at']}'";
        $where['group']      = "MONTH";
        $where['order']      = "order_create_time asc";
        $list                = $this->find($where)->toarray();
        $result              = [];
        if (!empty($list)) {
            foreach ($list as $val) {
                $result[$val['MONTH']] = $val['commition'];
            }
        }
        return $result;
    }

    public function orderCount($data = [])
    {
        $condition = "order_status in (1,2,4,6)";
        if (!empty($data)) {
            $condition .= " and order_create_time >= '{$data['start_at']}' and order_create_time <= '{$data['end_at']}'";
        }
        return $this::count($condition);
    }

    public function orderCompare($today, $lastday)
    {
        $condition = "order_create_time >= '{$today['start_at']}' and order_create_time <= '{$today['end_at']}' and order_status in (1,2,4,6)";
        $todayInfo = $this::count(
            $condition
        );
        $condition = "order_create_time >= '{$lastday['start_at']}' and order_create_time <= '{$lastday['end_at']}'  and order_status in (1,2,4,6)";
        $lastInfo  = $this::count(
            $condition
        );
        return $todayInfo - $lastInfo;
    }

    public function orderCountCommition($today)
    {
        $condition['conditions'] = "order_create_time >= '{$today['start_at']}' and order_create_time <= '{$today['end_at']}' and order_status in (1,2,4,6)";
        $condition['columns']    = 'sum(commition) as commition';
        $todayInfo               = $this::findFirst($condition);
        return $todayInfo->commition ? $todayInfo->commition : 0;
    }

    public function orderCompareCommition($today, $lastday)
    {
        $condition['conditions'] = "order_create_time >= '{$today['start_at']}' and order_create_time <= '{$today['end_at']}' and order_status in (1,2,4,6)";
        $condition['columns']    = 'sum(commition) as commition';
        $todayInfo               = $this::findFirst($condition);
        $condition['conditions'] = "order_create_time >= '{$lastday['start_at']}' and order_create_time <= '{$lastday['end_at']}' and order_status in (1,2,4,6)";
        $condition['columns']    = 'sum(commition) as commition';
        $lastInfo                = $this::findFirst($condition);
        return $todayInfo->commition - $lastInfo->commition;
    }

    public function order_count($uid)
    {
        $where['conditions'] = "user_id = $uid";
        $where['columns']    = 'count(id) as count';
        $count               = $this->findFirst($where);
        return $count->count ? $count->count : 0;
    }

    public function order_sum()
    {
        $conditions = 'order_status in (2,4,6)';
        return $this::SUM(array(
            $conditions,
            'column' => 'commition'
        ));
//        $sum = ;
    }


    public function get_count_list($data)
    {
        $conditions = 'id>0 ';

        $page = isset($data['page']) ? $data['page'] : 1;
        $size = 10;
        if ($page > 0) {
            $page = ($page - 1) * $size;
        }
        $fitst['group']   = 'user_id';
        $fitst['columns'] = 'user_id';
        $count            = $this::find($fitst)->toarray();
        $result['count']  = count($count);
        $result['list']   = [];
        if ($result['count'] > 0) {
            $result['list'] = $this::find(
                array(
                    $conditions,
                    "columns" => 'count(id) as count,user_id',
                    'limit'   => $size,
                    'offset'  => $page,
                    'group'   => 'user_id',
                    'order'   => 'count ' . $data['sort'],
                ))->toarray();
        }
        return $result;
    }

    public function moneyAll($params = [])
    {
        $where['conditions'] = 'order_status in (2,4,6)';
        if (isset($params['start_at']) && !empty($params['start_at'])) {
            $where['conditions'] .= " and order_create_time >= '{$params['start_at']}'";
        }
        if (isset($params['end_at']) && !empty($params['end_at'])) {
            $where['conditions'] .= " and order_create_time <= '{$params['end_at']}'";
        }
        $where['columns'] = "sum(commition) as money";
        $money            = $this->findFirst($where);
        return $money->money ? $money->money : 0;
    }

    public function frozenAll()
    {
        return 0;
    }

    public function orderCountInfo($params)
    {
        $params['end_at'] = $params['end_at'] . ' 23:59:59';
        $sql              = "SELECT COUNT(id) AS count ,DATE_FORMAT(order_create_time,'%Y-%m-%d') AS `day` FROM `w_union_order` where order_create_time >= '{$params['start_at']}' and order_create_time <= '{$params['end_at']}' and order_status in (2,4,6) GROUP BY `day` order by `day` asc ";
        $list             = $this->getDI()->get('dbMaster')->fetchAll($sql);
        $result           = [];

        if (!empty($list)) {
            foreach ($list as $val) {
                $result[$val['day']] = $val;
            }
        }
        return $result;
    }

    public function orderDayCount($params)
    {
        $where['conditions'] = "order_create_time >= '{$params['start_at']}' and order_create_time <= '{$params['end_at']}' and order_status in (2,4,6) ";
        $where['columns']    = "count(*) as count";
        $count               = $this->findFirst($where);
        return $count->count ? $count->count : 0;
    }


    public function orderDayCount_all()
    {
        $where['conditions'] = "order_status in (2,4,6) ";
        $where['columns']    = "count(*) as count";
        $count               = $this->findFirst($where);
        return $count->count ? $count->count : 0;
    }



    //根据日期查找
    public function datetime_day($datetime, $status = "", $filed = "")
    {
        $datetime['start_at'] = $datetime['start_at'] . ' 00:00:00';
        $datetime['end_at']   = $datetime['end_at'] . ' 23:59:59';
        //预估 和结算
        if ($filed) {
            $conditions = "order_earning_time>='{$datetime['start_at']}' and order_earning_time<='{$datetime['end_at']}'";
            if ($status) {
                $conditions .= " AND order_status in({$status})";
            }
            $phql = "SELECT DATE_FORMAT( order_earning_time, '%Y-%m-%d' ) AS datetime,sum(commition) as datacount FROM `w_union_order`  where {$conditions} GROUP BY DATE_FORMAT( order_earning_time, '%Y-%m-%d' )";
        } else {
            $conditions = "order_create_time>='{$datetime['start_at']}' and order_create_time<='{$datetime['end_at']}'";
            if ($status) {
                $conditions .= " AND order_status in({$status})";
            }
            $phql = "SELECT DATE_FORMAT( order_create_time, '%Y-%m-%d' ) AS datetime,sum(commition) as datacount FROM `w_union_order`  where {$conditions} GROUP BY DATE_FORMAT( order_create_time, '%Y-%m-%d' )";
        }
        $items    = $this->getDI()->get('dbMaster')->fetchAll($phql);
        $new_date = [];
        foreach ($items as $key => $value) {
            $new_date[$value['datetime']] = $value['datacount'];
        }
        return $new_date;
    }


    //预估收益
    public function estimate_function($datetime)
    {
        $conditions = "order_create_time>='{$datetime['start_at']}' and order_create_time<='{$datetime['end_at']}' and order_status in(2,4,6) ";
        $result     = $this->sum(array(
            $conditions,
            "column" => "commition",
        ));
        return $result ? $result : '0';
    }


    //结算收益
    public function settle_function($datetime)
    {
        $conditions = "order_earning_time>='{$datetime['start_at']}' and order_earning_time<='{$datetime['end_at']}' and order_status in(2,4,6) ";
        $result     = $this->sum(array(
            $conditions,
            "column" => "commition",
        ));
        return $result ? $result : '0';
    }


    //所有结算收益
    public function settle_function_sum()
    {
        $conditions = "order_status in(4,6) AND order_earning_time is not null";
        $result     = $this->sum(array(
            $conditions,
            "column" => "commition",
        ));
        return $result ? $result : '0';
    }



}
